package com.gxb.codebook;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.gxb.codebook.adapter.NotepadAdapter;
import com.gxb.codebook.bean.NotepadBean;
import com.gxb.codebook.database.SQLiteHelper;

import java.util.List;

public class RandomActivity extends AppCompatActivity {

    private Spinner generate_spinner;
    private TextView generate_text;
    private EditText one_generate;
    private EditText user;
    private EditText name;
    private EditText passwd;
    private EditText text;
    private Button one_generate_button;
    private Button name_copy;
    private Button passwd_copy;
    private Button text_copy;
    private Button out_btn;
    private Button baocun_btn;
    private NotepadAdapter adapter;
    private List<NotepadBean> notepadList;
    private SQLiteHelper dbHelper;
    private BroadcastReceiver themeChangeReceiver;
    private LocalBroadcastManager localBroadcastManager;

    @SuppressLint("UnspecifiedRegisterReceiverFlag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_random);
        dbHelper = new SQLiteHelper(this);

        // 初始化LocalBroadcastManager
        localBroadcastManager = LocalBroadcastManager.getInstance(this);

        // 初始化广播接收器
        themeChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ("THEME_CHANGED".equals(intent.getAction())) {
                    recreate();
                }
            }
        };

        // 注册广播接收器
        IntentFilter filter = new IntentFilter("THEME_CHANGED");
        localBroadcastManager.registerReceiver(themeChangeReceiver, filter);

        generate_spinner = findViewById(R.id.generate_spinner);
        generate_text = findViewById(R.id.generate_text);
        one_generate = findViewById(R.id.one_generate);
        one_generate_button = findViewById(R.id.one_generate_button);
        user = findViewById(R.id.user);
        name = findViewById(R.id.name);
        passwd = findViewById(R.id.passwd);
        text = findViewById(R.id.text);
        name_copy = findViewById(R.id.name_copy);
        passwd_copy = findViewById(R.id.passwd_copy);
        text_copy = findViewById(R.id.text_copy);
        baocun_btn = findViewById(R.id.baocun_btn);
        out_btn = findViewById(R.id.out_btn);

        one_generate_button.setOnClickListener(v -> one_generate_buttons());
        initSpinnerForDropdown();

        View[] views = {name_copy, passwd_copy, text_copy};
        TextView[] textViews = {name, passwd, text};

        for (int i = 0; i < views.length; i++) {
            int finalI = i;
            views[i].setOnClickListener(v -> copyText(textViews[finalI].getText().toString()));
        }

        out_btn.setOnClickListener(v -> outbtn());
        baocun_btn.setOnClickListener(v -> baocunbtn());
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (localBroadcastManager != null && themeChangeReceiver != null) {
            localBroadcastManager.unregisterReceiver(themeChangeReceiver);
        }
    }

    private void outbtn() {
        // 发送关闭随机密码生成器活动的广播
        Intent closeIntent = new Intent("RANDOM_ACTIVITY_CLOSED");
        localBroadcastManager.sendBroadcast(closeIntent);

        finish();
    }

    private void copyText(String string) {
        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData clip = ClipData.newPlainText("label", string);
        clipboard.setPrimaryClip(clip);
        Toast.makeText(this, "已复制到剪贴板", Toast.LENGTH_SHORT).show();

        // 发送文本复制成功的广播
        Intent copyIntent = new Intent("TEXT_COPIED");
        copyIntent.putExtra("text", string);
        localBroadcastManager.sendBroadcast(copyIntent);
    }

    private void one_generate_buttons() {
        String inputNumber = one_generate.getText().toString();
        int level = generate_spinner.getSelectedItemPosition();
        if (TextUtils.isEmpty(inputNumber)) {
            Toast.makeText(this, "密码个数为空", Toast.LENGTH_SHORT).show();

            // 发送生成密码失败的广播 - 密码个数为空
            Intent failIntent = new Intent("PASSWORD_GENERATE_FAILED");
            failIntent.putExtra("reason", "密码个数为空");
            localBroadcastManager.sendBroadcast(failIntent);

            return;
        }
        int length = Integer.parseInt(inputNumber);
        String[] passwords = generateRandomPasswords(length, level);
        name.setText(passwords[0]);
        passwd.setText(passwords[1]);
        text.setText(passwords[2]);

        // 发送密码生成成功的广播
        Intent successIntent = new Intent("PASSWORD_GENERATED");
        successIntent.putExtra("length", length);
        successIntent.putExtra("level", level);
        localBroadcastManager.sendBroadcast(successIntent);
    }

    private String[] generateRandomPasswords(int length, int level) {
        String[] chars;
        switch (level) {
            case 0:
                chars = new String[]{"abcdefghijklmnopqrstuvwxyz", "0123456789"};
                break;
            case 1:
                chars = new String[]{"abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "0123456789"};
                break;
            case 2:
                chars = new String[]{"abcdefghijklmnopqrstuvwxyz", "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "0123456789", ".@$!%*#_~?&^"};
                break;
            default:
                throw new IllegalArgumentException("Invalid level");
        }

        String[] passwords = new String[3];
        for (int i = 0; i < 3; i++) {
            StringBuilder password = new StringBuilder();
            for (int j = 0; j < length; j++) {
                String charSet = chars[(int) (Math.random() * chars.length)];
                password.append(charSet.charAt((int) (Math.random() * charSet.length())));
            }
            passwords[i] = password.toString();
        }

        return passwords;
    }

    private String[] starArray = {"简单", "中等", "复杂"};

    private void initSpinnerForDropdown() {
        // 创建自定义的ArrayAdapter
        ArrayAdapter<String> starAdapter = new ArrayAdapter<String>(this, R.layout.spinner_item, starArray) {
            @Override
            public View getDropDownView(int position, View convertView, android.view.ViewGroup parent) {
                View view = super.getDropDownView(position, convertView, parent);
                // 设置下拉列表项的背景颜色
                view.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.white_600));
                // 设置文本颜色
                ((TextView) view).setTextColor(ContextCompat.getColor(getContext(), R.color.blue_200));
                return view;
            }

            @Override
            public View getView(int position, View convertView, android.view.ViewGroup parent) {
                View view = super.getView(position, convertView, parent);
                // 设置Spinner显示项的文本颜色
                ((TextView) view).setTextColor(ContextCompat.getColor(getContext(), R.color.blue_400));
                return view;
            }
        };

        Spinner generate_spinner = findViewById(R.id.generate_spinner);
        generate_spinner.setPrompt("请选择复杂度");
        generate_spinner.setAdapter(starAdapter);
        generate_spinner.setSelection(0);

        // 设置Spinner的背景
        generate_spinner.setBackgroundColor(ContextCompat.getColor(this, R.color.white_600));

        // 设置Spinner弹出框的背景
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            generate_spinner.setPopupBackgroundDrawable(ContextCompat.getDrawable(this, R.drawable.homecolor));
        }

        generate_spinner.setOnItemSelectedListener(new MySelectedListener());
    }

    private class MySelectedListener implements AdapterView.OnItemSelectedListener {
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
            RandomActivity activity = (RandomActivity) arg0.getContext();
            switch (arg2) {
                case 0:
                    activity.generate_text.setText("简单：随机小写字母+数字组合");
                    break;
                case 1:
                    activity.generate_text.setText("中等：随机大小写字母+数字组合");
                    break;
                case 2:
                    activity.generate_text.setText("复杂：随机大小写字母+数字组合+特殊符号");
                    break;
            }

            // 发送复杂度选择变更的广播
            Intent selectIntent = new Intent("PASSWORD_COMPLEXITY_SELECTED");
            selectIntent.putExtra("level", arg2);
            localBroadcastManager.sendBroadcast(selectIntent);
        }
        public void onNothingSelected(AdapterView<?> arg0) {}
    }

    private void baocunbtn() {
        String userText = user.getText().toString();
        String nameText = name.getText().toString();
        String passwdText = passwd.getText().toString();
        String textText = text.getText().toString();
        dbHelper.insertNotepad(userText, nameText, passwdText, textText);

        // 发送密码保存成功的广播
        Intent saveIntent = new Intent("PASSWORD_SAVED");
        saveIntent.putExtra("user", userText);
        saveIntent.putExtra("name", nameText);
        localBroadcastManager.sendBroadcast(saveIntent);

        Intent intent = new Intent(this, HomeActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);

        // 发送跳转到主页的广播
        Intent navigateIntent = new Intent("NAVIGATE_TO_HOME");
        localBroadcastManager.sendBroadcast(navigateIntent);
    }
}
